import axios from 'axios';
import * as constants from './constants';

const changeDetail = (data) => ({
  type: constants.GET_SETTINGSDATA,
  settingsData: data
});

const changePanel = () => ({
  type: constants.GET_PANELDATA,
  dialogVisible: false
});

// 初始数据获取 settingsData
export const getSettingsData = () => {
  let id = localStorage.getItem("id");
  return (dispatch) => {
    axios.get('http://localhost:9080/users/'+id, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token")
      }
    }).then((res) => {
      dispatch(changeDetail(res.data));
    }).catch(() => {
      console.log('error');
    })
  }
}

// edit panel/dialog part
export const handleOpenEditPanel = () => ({
  type: constants.OPEN_EDITPANEL,
  dialogVisible: true
});

export const handleCloseEditPanel = () => ({
  type: constants.CLOSE_EDITPANEL,
  dialogVisible: false
});

export const submitEdit = (data) => {
  let readyData = JSON.stringify({
    username: data.username
  });
  return (dispatch) => {
    axios.put('http://localhost:9080/users/me', readyData, {
      headers: {
        'Authorization': "Bearer " + localStorage.getItem("access_token"),
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }).then((res) => {
      alert('修改成功！');
      dispatch(changePanel());
    }).catch(() => {
      console.log('error');
    })
  }
}